//
//  ColorPickerViewModel.swift
//  PorscheRegistration
//
//  Created by Jinzhu Liu on 2023/11/18.
//

import Foundation
import Combine

protocol ColorPickerViewModelInputType {
    func start()
    func selected(item: ColorPickerCellViewModelType)
}

protocol ColorPickerViewModelOutputType {
    var updateColorItemsPublisher: AnyPublisher<[ColorPickerCellViewModelType], Never> { get }
    var selectedColorPublisher: AnyPublisher<AvatarColor, Never> { get }
    
    var dismissPublisher: AnyPublisher<Void, Never> { get }
}

protocol ColorPickerViewModelType {
    var input: ColorPickerViewModelInputType { get }
    var output: ColorPickerViewModelOutputType { get }
}

class ColorPickerViewModel: ColorPickerViewModelType,
                            ColorPickerViewModelOutputType {
    var dismissPublisher: AnyPublisher<Void, Never>
    private var dismissViewSubject = PassthroughSubject<Void, Never>()
    
    var selectedColorPublisher: AnyPublisher<AvatarColor, Never>
    private var selectedColorSubject = PassthroughSubject<AvatarColor, Never>()
    
    var updateColorItemsPublisher: AnyPublisher<[ColorPickerCellViewModelType], Never>
    private var updateColorItemsSubject = PassthroughSubject<[ColorPickerCellViewModelType], Never>()

    var input: ColorPickerViewModelInputType { self }
    var output: ColorPickerViewModelOutputType { self }
    
    init() {
        updateColorItemsPublisher = updateColorItemsSubject.eraseToAnyPublisher()
        selectedColorPublisher = selectedColorSubject.eraseToAnyPublisher()
        dismissPublisher = dismissViewSubject.eraseToAnyPublisher()
    }
    
    private func generateColorItems() {
        let colorItems = [
            ColorPickerCellViewModel(color: .red, name: "Red"),
            ColorPickerCellViewModel(color: .yellow, name: "Yellow"),
            ColorPickerCellViewModel(color: .blue, name: "Blue"),
            ColorPickerCellViewModel(color: .green, name: "Green")
        ]
        updateColorItemsSubject.send(colorItems)
    }
}

extension ColorPickerViewModel: ColorPickerViewModelInputType {
    func start() {
        generateColorItems()
    }
    
    func selected(item: ColorPickerCellViewModelType) {
        selectedColorSubject.send(item.output.dataModel)
        dismissViewSubject.send(())
    }
}
